package com.example.sharesinfo.fragment.index;


import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import de.hdodenhof.circleimageview.CircleImageView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.FocusBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.manager.UserManager;
import com.example.sharesinfo.model.FocusModel;
import com.example.sharesinfo.ui.NewsInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.utils.TimeUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class FocusOnFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private boolean isPrepared = false;     //标志位，标志已经初始化完成
    private LinearLayout ll_dialog;
    private View item_empty_view;
    private RecyclerView mvFocusView;
    private SwipeRefreshLayout mFocusRefreshLayout;
    private CommonAdapter<FocusModel> mFocusAdapter;
    private List<FocusModel> mList = new ArrayList<>();
    //TalkId=***&UserId=***
    private String SendTalkPraiseUrl = "http://119.23.221.142/api/talk/SendTalkPraise?";
    private Map<String, String> praiseDatas = new HashMap<>();
    //TalkId=***&UserId=***
    private String CancelTalkPraiseURl = "http://119.23.221.142/api/talk/CancelTalkPraise?";
    private Map<String, String> CancelPraiseDatas = new HashMap<>();

    /**
     * 未做：不同类型的动态
     * 点击进入具体内容
     * 点赞、取消点赞
     * 评论、跳转
     */


    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            LogUtils.i("handleMessage" + msg.what);
            switch (msg.what) {
                case 200:
                    ll_dialog.setVisibility(View.GONE);
                    //请求成功
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    mFocusRefreshLayout.setRefreshing(false);
                    item_empty_view.setVisibility(View.GONE);
                    mvFocusView.setVisibility(View.VISIBLE);
                    FocusBean result = (FocusBean) msg.obj;
                    for (int i = 0; i < result.getData().size(); i++) {
                        FocusModel model = new FocusModel();
                        model.setTalkId(result.getData().get(i).getTalkId());
                        model.setUserId(result.getData().get(i).getUserId());
                        model.setNickname(result.getData().get(i).getUsername());
                        model.setTime(result.getData().get(i).getTalkTime());
                        model.setContent(result.getData().get(i).getContent());
                        model.setCommentNum(Integer.parseInt(result.getData().get(i).getCommentNumber()));
                        model.setUrl(result.getData().get(i).getImageUrl());
                        if (result.getData().get(i).getPictures().size() != 0) {
                            //有图片
                            model.setPicture(result.getData().get(i).getPictures().get(0));
                        } else {
                            model.setPicture("null");
                        }
                        model.setPraiseNum(Integer.parseInt(result.getData().get(i).getPraiseNumber()));
                        model.setReadNum(Integer.parseInt(result.getData().get(i).getReadNumber()));
                        model.setIf_Praise(result.getData().get(i).getIf_Priase());
                        mList.add(model);
                    }
                    mFocusAdapter.notifyDataSetChanged();
                    break;
                case 400:
                    ll_dialog.setVisibility(View.GONE);
                    mFocusRefreshLayout.setRefreshing(false);
                    item_empty_view.setVisibility(View.VISIBLE);
                    mvFocusView.setVisibility(View.GONE);
                    break;
                case 404:
                    break;
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_focus_on, null);

        initView(view);
        initData();
        return view;
    }

    private void initData() {


    }

    private void initView(final View view) {
        LogUtils.i("关注事件处理：" + SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        ll_dialog = view.findViewById(R.id.ll_dialog);
        ll_dialog.setVisibility(View.VISIBLE);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        mFocusRefreshLayout = view.findViewById(R.id.mFocusRefreshLayout);
        mvFocusView = view.findViewById(R.id.mFocusView);
        //下拉刷新
        mFocusRefreshLayout.setOnRefreshListener(this);

        mvFocusView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mvFocusView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mFocusAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<FocusModel>() {


            @Override
            public void onBindViewHolder(final FocusModel model, final CommonViewHolder viewHolder, int type, int position) {
                LogUtils.i("是否点赞：" + model.getIf_Praise());
                final ImageView praised = viewHolder.getView(R.id.iv_praised);
                if (praiseDatas.size() > 0) {
                    praiseDatas.clear();
                }
                if (CancelPraiseDatas.size() > 0) {
                    CancelPraiseDatas.clear();
                }
                if (!model.getIf_Praise().equals("False")) {
                    praised.setImageResource(R.drawable.praise_checked);
                    praised.setTag("checked");
                }
                final int[] praise = {model.getPraiseNum()};
                viewHolder.setImageUrl(getContext(), R.id.focus_on_head_portrait, model.getUrl());
                viewHolder.getView(R.id.focus_on_head_portrait).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtils.i("用户id：" + model.getUserId());
                        UserManager.getInstance().queryUserInfo(model.getUserId(), getContext());
                    }
                });
                viewHolder.setText(R.id.focus_on_username, model.getNickname());
                viewHolder.setText(R.id.focus_on_time, model.getTime());
                viewHolder.setText(R.id.focus_on_contents, model.getContent());
                ImageView iv_img = viewHolder.getView(R.id.iv_img);
                if (model.getPicture().equals("null")) {
                    iv_img.setVisibility(View.GONE);
                } else {
                    iv_img.setVisibility(View.VISIBLE);
                    viewHolder.setImageUrl(getContext(), R.id.iv_img, model.getPicture());
                }

                viewHolder.setText(R.id.focus_on_number_of_comments, model.getCommentNum() + "评");
                viewHolder.setText(R.id.focus_on_number_of_praised, model.getPraiseNum() + "赞");
                viewHolder.setText(R.id.focus_on_number_of_read, model.getReadNum() + "人已阅读");

                praised.setOnClickListener(new View.OnClickListener() {
                    //点赞事件
                    @Override
                    public void onClick(View v) {
                        if (praised.getTag().equals("unchecked")) {
                            praised.setImageResource(R.drawable.praise_checked);
                            praise[0] += 1;
                            viewHolder.setText(R.id.focus_on_number_of_praised, praise[0] + "赞");
                            praised.setTag("checked");
                            //TalkId=***&UserId=***
                            praiseDatas.put("TalkId", String.valueOf(model.getTalkId()));
                            praiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(SendTalkPraiseUrl, null,
                                    praiseDatas, null, null,
                                    new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "点赞失败");
                                        }
                                    });
                        } else if (praised.getTag().equals("checked")) {
                            LogUtils.i("点赞事件处理" + "取消点赞");
                            praised.setImageResource(R.drawable.praise_unchecked);
                            praise[0] -= 1;
                            viewHolder.setText(R.id.focus_on_number_of_praised, praise[0] + "赞");
                            praised.setTag("unchecked");
                            //TalkId=***&UserId=***
                            CancelPraiseDatas.put("TalkId", String.valueOf(model.getTalkId()));
                            CancelPraiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(CancelTalkPraiseURl, null,
                                    CancelPraiseDatas, null, null, new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "取消点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "取消点赞失败");
                                        }
                                    });

                        }
                        Toast.makeText(getContext(), "Id:" + "点赞", Toast.LENGTH_SHORT).show();
                    }
                });
                TextView content = viewHolder.getView(R.id.focus_on_contents);
                content.setOnClickListener(new View.OnClickListener() {
                    //点击内容，跳转到详情
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getContext(), "Id:" + "内容详情", Toast.LENGTH_SHORT).show();
                    }
                });
                ImageView comment = viewHolder.getView(R.id.iv_comment);
                comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //点击评论，跳转到详情，同点击内容
                        Toast.makeText(getContext(), "Id:" + "评论", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.focus_item;
            }
        });
        mvFocusView.setAdapter(mFocusAdapter);

    }

    /**
     * @type
     * @explain 根据用户id  查询关注
     * @author
     * @creat time
     */

    private void queryFocus(String userId) {
        LogUtils.i("get http" + "queryFocus");
        String url = "http://119.23.221.142/api/user/GetAllFollowUsers?UserId=" + userId;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message mess = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);

                LogUtils.i("JSON返回:" + object.getString("data"));
                if (object.getString("data").equals("{}")) {
                    mess.what = 400;
                    mHandler.sendMessage(mess);
                } else {
                    FocusBean bean = new Gson().fromJson(s, FocusBean.class);
                    if (CommonUtils.isEmpty(bean.getData())) {
                        mess.what = code;
                        mess.obj = bean;
                    } else {
                        mess.what = 404;
                    }
                    mHandler.sendMessage(mess);
                }

            }

            @Override
            public void OnFailed(String s) {

            }
        });
    }

    @Override
    public void onRefresh() {
        if (mFocusRefreshLayout.isRefreshing()) {
            queryFocus(SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));

        }
    }


    @Override
    public void onResume() {
        if (!isPrepared) {
            isPrepared = true;
            queryFocus(SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        }
        super.onResume();

    }
}
